<template>
  <!-- 添加用户 弹窗 -->
  <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" v-model="dialogVisible">
    <el-form ref="formRef" class="p-3" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称" autocomplete="off" :readonly="true" @focus="removeReadonly" />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="密码" prop="password" autocomplete="off" :readonly="true" @focus="removeReadonly">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" show-password />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择">
          <el-option label="男" :value="true" />
          <el-option label="女" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="角色" prop="roleId">
        <el-select filterable v-model="form.roleId" placeholder="请选择">
          <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="form.type!=1" label="组织" prop="departmentId">
        <el-tree-select
          class="avatar-uploader"
          :props="defaultProps"
          v-model="form.departmentId"
          :data="treeData"
          filterable
          check-strictly
          :render-after-expand="false"
        >
        </el-tree-select>
      </el-form-item>
      <el-form-item label="用户备注" prop="remark">
        <el-input :rows="2" type="textarea" maxlength="255" show-word-limit v-model="form.remark" placeholder="请输入用户备注" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          list-type="picture-card"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="headers"
        >
          <img v-if="form.avatar" :src="form.avatar" class="w-25 h-25" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, defineEmits, defineProps, onMounted } from "vue";
import { addUser, updateUser, getUserById } from "@/api/modules/user";
import { getDictByCode } from "@/api/modules/dict";
import { getDepartmentTree } from "@/api/modules/department";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const userStore = useUserStore();
const headers =  ref({
  Authorization: `Bearer ${userStore.token}`
});
const props = defineProps({
  id: {
    type: String,
    default: ""
  }
});

const dialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  username: "", //用户名
  nickname: "", //昵称
  avatar: "", //头像
  password: "", //密码
  confirmPassword: "", //确认密码
  gender: false, //性别
  phone: "", //手机号
  departmentId: "", //组织id
  roleId: "", //角色id
  remark: "", //备注
  type: 0
});
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 5, max: 16, message: "用户名长度在 5 到 16 个字符", trigger: "blur" },
    { pattern: /^[a-z]+$/, message: "必须是小写英文", trigger: "blur" }
  ],
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 16, message: "昵称长度在 2 到 16 个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()\-_=+{};:,<.>]).+$/,
      message: "密码必须包含特殊字符以及大小写字母",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  departmentId: [{ required: true, message: "请选择组织", trigger: "change" }],
  remark: [{ max: 255, message: "长度不能超过 255 个字符", trigger: "blur" }]
};

const setDepartment = departmentId => {
  form.value.departmentId = departmentId;
};
const isEdit = ref(false);
const emit = defineEmits(["cancel", "confirm"]);

const handleCancel = () => {
  emit("cancel");
  dialogVisible.value = false;
};

const handleConfirm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (!isEdit.value) {
        form.value.pid = props.id;
      }
      const apiCall = isEdit.value ? updateUser : addUser;
      apiCall(form.value).then(res => {
        if (res.code === 200) {
          emit("confirm");
          ElMessage.success(isEdit.value ? "编辑成功！" : "添加成功！");
          dialogVisible.value = false;
          formRef.value.resetFields();
        }
      });
    }
  });
};

const openDialog = id => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  dialogVisible.value = true;
  if (id) {
    isEdit.value = true;
    getUserById(id).then(res => {
      form.value = res.data;
    });
  } else {
    isEdit.value = false;
    form.value = {
      username: "", //用户名
      nickname: "", //昵称
      avatar: "", //头像
      password: "", //密码
      confirmPassword: "", //确认密码
      gender: true, //性别
      phone: "", //手机号
      departmentId: "", //组织id
      roleId: "", //角色id
      remark: "", //备注
      type: 0
    };
  }
};

const uploadUrl = "/admin/file/upload";
const handleAvatarSuccess = res => {
  form.value.avatar = res.data;
};
const beforeAvatarUpload = file => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
};
const roleList = ref([]);
const treeData = ref([]);
const defaultProps = {
  label: "departmentName",
  value: "id"
};
const removeReadonly = event => {
  event.target.readOnly = false;
};
onMounted(() => {
  //获取角色列表
  getDictByCode({ dictCode: "role" }).then(res => {
    roleList.value = res.data.others;
  });
  //获取组织树
  getDepartmentTree().then(res => {
    treeData.value = res.data;
  });
});
defineExpose({
  setDepartment,
  openDialog
});
</script>
